package com.sq.partner.manager.controller.credit;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.sq.partner.manager.common.Constants;
import com.sq.partner.manager.common.DictCache;
import com.sq.partner.manager.common.Result;
import com.sq.partner.manager.mybatis.model.CoreDept;
import com.sq.partner.manager.mybatis.model.DictDto;
import com.sq.partner.manager.mybatis.model.GatewayChannelInfo;
import com.sq.partner.manager.mybatis.model.GatewaySubChannel;
import com.sq.partner.manager.mybatis.model.GatewayUser;
import com.sq.partner.manager.mybatis.model.TradAgentInfo;
import com.sq.partner.manager.mybatis.model.TradAgentInfoRela;
import com.sq.partner.manager.mybatis.model.TradSaleAgent;
import com.sq.partner.manager.mybatis.model.TradePlanFee;
import com.sq.partner.manager.service.IFacadeUserService;
import com.sq.partner.manager.service.IGatewayAgentInfoMtService;
import com.sq.partner.manager.service.IGatewayChannelInfoConfigService;
import com.sq.partner.manager.service.IGatewayInsureService;
import com.sq.partner.manager.service.IGatewayLifePolicyListService;
import com.sq.partner.manager.service.IGatewaySubChannelService;
import com.sq.partner.manager.service.INlifePlanConfigService;
import com.sq.partner.manager.service.TradPlanFeeService;
import com.sq.partner.manager.service.credit.CreditInfomationService;
import com.sq.partner.manager.util.JsonUtils;
import com.sq.partner.manager.util.LogUtil;
import com.sq.partner.manager.util.Page;
import com.sq.partner.manager.util.StrUtil;

@Controller
@RequestMapping(value="/CreditChannel")
public class CreditChannelInformationController {
	private static Logger logger = LogUtil.getLog(CreditChannelInformationController.class);
	@Resource
	private IGatewayAgentInfoMtService agentInfoMtService;
	@Resource
	private IFacadeUserService facadeUserMtService;
	@Resource
	private IGatewaySubChannelService subChannelService;
	@Resource
	private IGatewayChannelInfoConfigService channelInfoConfigService;
	@Resource
	private INlifePlanConfigService nlifePlanConfigService;
	@Resource
	IGatewayInsureService gatewayInsureService;
	@Resource
	private IGatewayLifePolicyListService lifePolicyListService;
	@Resource
	private TradPlanFeeService tradPlanFeeService;
	@Resource
	private CreditInfomationService creditInfomationService;
	@RequestMapping(value = "/channelInformation")
	public String agentMtInfo(ModelMap model,HttpSession session) throws Exception {
		//页面初始化加载“代理类型”列表
		List<DictDto> agentTypeList = DictCache.getDict(Constants.DICT_SALE_AGENT_TYPE);
		
		//新业务来源
		List<DictDto> newBSList = DictCache.getDict(Constants.DICT_NEW_BUSINESS_SOURCE);
		//旧业务来源
		List<DictDto> oldBSList = DictCache.getDict(Constants.DICT_OLD_BUSINESS_SOURCE);
		//归属渠道
		List<DictDto> btcList = DictCache.getDict(Constants.DICT_BELONG_TO_CHANNEL);
		//渠道类型
		List<DictDto> channelList = DictCache.getDict(Constants.DICT_CHANNEL_TYPE);
		/*//联合出单方案
		List<DictDto> unionTypes=DictCache.getDict(Constants.DICT_UNION_TYPE);*/
		//分公司
		GatewayUser user=(GatewayUser) session.getAttribute(Constants.SESSION_USER);
		logger.info("当前登录用户的userCode为"+user.getUserCode()+",DepartmentStr:"+user.getDepartmentStr());
		
		if(null != user && StrUtil.isNotEmpty(user.getDepartmentStr())){
			model.put("branchList",lifePolicyListService.queryPrivilegeBranch(user.getDepartmentStr()));
		}
		
		model.put("newBSList", newBSList);
		model.put("oldBSList", oldBSList);
		model.put("btcList", btcList);
		model.put("channelList", channelList);
		model.put("agentTypeList", agentTypeList);
//		model.put("unionTypes", unionTypes);
		return "credit/channelInformation/channelInformation";
	}
	
	@RequestMapping(value = "/queryByCriteria", method = RequestMethod.POST)
	@ResponseBody
	public Page<TradAgentInfo> queryInfoByCriteria(HttpSession session,TradAgentInfo agentInfo,Integer pageIndex) throws Exception {
		Page<TradAgentInfo> page = new Page<TradAgentInfo>();
		page.setCurrent(pageIndex);
		page.setType(agentInfo);
		GatewayUser user = (GatewayUser)session.getAttribute(Constants.SESSION_USER);
		if(user!=null && StrUtil.isNotEmpty(user.getDepartmentStr())){
			logger.info("---come into agent successful param---");
			return agentInfoMtService.queryInfoByCriteria(page,user);
			
		}
		page.setResult("error");
		page.setMessage("用户所属机构权限不足，无权限使用该模块");
		return page;
	}
	
	/**
	 * 加载广东销售信息
	 * @param planNo
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/loadSale")
	@ResponseBody
	public Map<String,Object> loadSale(String id) throws Exception{
		Map<String, Object> map = new HashMap<String,Object>();
		try {
			/**销售人员字典*/
			List<DictDto> saleMenTypes=DictCache.getDict(Constants.DICT_SALE_MEN_TYPE);
			List<DictDto> saleTypes=DictCache.getDict(Constants.DICT_SALES_TYPE);
			List<DictDto> roleTypes=DictCache.getDict(Constants.DICT_ROLE_STYPE);/**新意健险销售人员类别*/
			List<TradSaleAgent> saleAgents=agentInfoMtService.queryTrandSaleAgent(id);
			map.put("saleMenTypes", saleMenTypes);
			map.put("saleTypes", saleTypes);
			map.put("saleAgents", saleAgents);
			map.put("roleTypes", roleTypes);
			map.put("success", true);
		} catch (Exception e) {
			map.put("success", false);
			map.put("message", e.getMessage());
		}
		return map;
	}
	/**
	 * 加载子机构列表，需要传入页面选择的“合作伙伴代码”进行查询
	 */
	@RequestMapping(value = "/loadSubChannelInfo")
	public @ResponseBody Page<GatewaySubChannel> loadSubChannelInfo(Integer size,Integer pageIndex,String subChannelCode,String subChannelName,String channelCode) throws Exception{
		Page<GatewaySubChannel> page = new Page<GatewaySubChannel>();
		if(StrUtil.isEmpty(channelCode)){
			page.setResult("error");
			page.setMessage("合作伙伴不能为空，请选择");
			return page;
		}
		page.setCurrent(pageIndex);
		page.setSize(size);
		GatewaySubChannel subChannelInfo = new GatewaySubChannel();
		subChannelInfo.setSubChannelCode(subChannelCode);
		subChannelInfo.setSubChannelName(subChannelName);
		subChannelInfo.setParentChannelCode(channelCode);
		page.setType(subChannelInfo);
		Page<GatewaySubChannel> p=agentInfoMtService.queryPageForGatewaySubChannelInfo(page);
		return p;
	}
	@RequestMapping(value = "/saveAgentMtInfo", method = RequestMethod.POST)
	@ResponseBody
	public Result saveAgentMtInfo(HttpSession session,String flag, String agentType,
			String userCode, String channelCode, String subChannelCode,
			String dptCde, String agentNo, String protocolNo,
			String serviceCode,String serviceName, String empNo,String empName, String teamCode, String teamName,
			String userName, String cardApplicant,String channleCode,
			String channleType,String newBsnsType,String categoryCode,
			String zone,String organization,String branch,String branchName,Long id,String transType,String cbrkrname,String coprcod,
			String key1,String key2,String key3,String key4,String key5,String unionType,
			String manag_code,String manag) throws Exception {
		if(StrUtil.isEmpty(flag)){
			return Result.error("系统正忙，请稍后重试...");
		}else if(StrUtil.isEmpty(agentType)){
			return Result.error("销售类型不能为空");
		}else if("update".equals(flag) && (null == id)){
			return Result.error("操作失败，代理信息唯一标识不允许为空");
		}
		//对于子机构代理特殊处理
		if("4".equals(agentType)){
			if(StrUtil.isEmpty(branch)){
			return Result.error("网点代码不能为空");
			} else if(StrUtil.isEmpty(branchName)){
				return Result.error("网点名称不能为空");
			}
		}
		if(StrUtil.isEmpty(channleCode)){
			return Result.error("请选择归属渠道");
		}else if(StrUtil.isEmpty(channleType)){
			return Result.error("请选择渠道类型");
		}else if(StrUtil.isEmpty(newBsnsType)){
			return Result.error("请选择业务来源");
		}/*else if(StrUtil.isEmpty(categoryCode)){
			return Result.error("请选择原业务来源");
		}*/
		if(StrUtil.isEmpty(serviceCode)){
			return Result.error("服务代码 不能为空");
		}
		GatewayUser user = (GatewayUser)session.getAttribute(Constants.SESSION_USER);
		return creditInfomationService.saveAgentMtInfoAsCredit(flag, agentType, userCode, channelCode, subChannelCode, 
													dptCde, agentNo, protocolNo, serviceCode,serviceName, empNo,empName, teamCode, teamName, userName, cardApplicant, channleCode, channleType, newBsnsType, categoryCode, 
													zone, organization, branch, branchName, id, user,cbrkrname,coprcod,key1,key2,key3,key4,key5,unionType,
													manag_code,manag);
				
	}
	@RequestMapping(value="/queryUsercodeIsExists")
	public @ResponseBody Result checkUsercodeBeforeAdd(String userCode) throws Exception {
		TradAgentInfo tradAgentMtInfo = new TradAgentInfo();
		tradAgentMtInfo.setUserCode(userCode);
		TradAgentInfo ur = agentInfoMtService.queryAgentInfoByCode(tradAgentMtInfo);
		if(ur!=null){
			logger.info("---------------代理用户名已存在------------------");
			return Result.error("该代理用户名已存在,请更换");
		}else{
			return null;
		}
	}
	@RequestMapping(value = "/deleteAgentMtInfoById", method = RequestMethod.POST)
	@ResponseBody
	public Result deleteAgentMtInfoById(Long id,String agentType,String userCode,String subChannelCode,String transType,String channelCode) throws Exception {
		if(StrUtil.isEmpty(id)){
			return Result.error("代理人编码不能为空");
		}else if(StrUtil.isEmpty(agentType)){
			return Result.error("代理人类型不能为空");
		}else if(agentInfoMtService.checkIsExistConfigPlanInfo(id)>0){
			return Result.error("此代理信息已关联到投保方案，不能删除!");
		}
		//根据类型后台删除插入的数据：删除中间关系表
		//个人
		if("3".equals(agentType)){
			if(StrUtil.isEmpty(userCode)){
				return Result.error("用户名不能为空");
			}
			facadeUserMtService.delUserByUserCodeAndUserType(userCode, agentType);
		}
		//总对总
		if("4".equals(agentType)){
			if(StrUtil.isEmpty(subChannelCode)){
				return Result.error("子机构代码不能为空");
			}
			facadeUserMtService.delUserBySubChannelCodeAndUserType(subChannelCode, agentType);
			Map<String, String> map =new HashMap<String, String>();
			map.put("subChannelCode", subChannelCode);
			map.put("fkChannelCode", channelCode);
			subChannelService.delSubChannel1(map);
		}
		TradAgentInfo agent = new TradAgentInfo();
		agent.setId(id);
		boolean agencyR = agentInfoMtService.deleteAgentMtInfo(agent);
		if(agencyR)
		{
			/**删除费用跟单信息*/
			agentInfoMtService.deleteTrade(id+"");
			return Result.success("删除成功！");
		}
		return Result.error("删除失败！");
	}
	
	/**
	 * 代理类型模板下载
	 */
	@RequestMapping(value = "/downloadUserTemplet", method = RequestMethod.GET)
	public void downloadUserTemplet(HttpServletResponse response,HttpServletRequest request ,String templateType) throws IOException{
		String classPath=this.getClass().getResource("").getPath();
		String path="";
		if(StrUtil.isEmpty(templateType)){
			logger.info("销售业务信息维护--下载模板，模板类型传入参数为空结束程序");
			return ;
		}else if("credit".equals(templateType)){
			path = (classPath.substring(0,classPath.indexOf("/WEB-INF/")+8)+ "/file/creditAgent_templet.xls").replace("/WEB-INF", "");
		}else{
			logger.info("销售业务信息维护--下载模板，模板类型传入参数为非法参数结束程序");
			return ;
		}
		// 以流的形式下载文件
		InputStream inputStream=null;
		OutputStream outputStream =null;
		try {
			File file = new File(path);
			// 取得文件名。
			String filename = file.getName();
			inputStream = new BufferedInputStream(new FileInputStream(path));
			byte[] buffer = new byte[inputStream.available()];
			inputStream.read(buffer);
			//清空response
			response.reset();
			//设置response的Header
			response.addHeader("Content-Disposition", "attachment;filename=" + new String(filename.getBytes()));
			response.addHeader("Content-Length", "" + file.length());
			outputStream = new BufferedOutputStream(response.getOutputStream());
			response.setContentType("application/octet-stream");
			outputStream.write(buffer);
			outputStream.flush();
		}catch (Exception e) {
			logger.info(e);
		}finally{
			if(null!=inputStream){
				inputStream.close();
			}
			if(null!=outputStream){
				outputStream.close();
			}
		}
	}
	
	/**
	 * excel上传
	 */
	@RequestMapping(value = "/xlsImportAgentInfoFileUpload")
	public void addUserAgentInfo(@RequestParam MultipartFile[] myfiles,HttpServletResponse response, HttpSession session,String agentType) throws Exception {
		response.setContentType("text/html");
		response.setCharacterEncoding("UTF-8");
		PrintWriter out = null;
		List<InputStream> inputStreams = null;
		Page<String>  page = new Page<String>();
		// 上传文件的原名(即上传前的文件名字)
		try {
			out = response.getWriter();
			if (myfiles.length < 1) {
				page.setResult("error");
				page.setMessage("请添加上传文件!");
			}else if(StrUtil.isEmpty(agentType)){
				page.setResult("error");
				page.setMessage("上传excel销售类型参数不能为空，请稍后重试");
			}else if(!("3".equals(agentType)) && !("4".equals(agentType)) && !("5".equals(agentType))){
				page.setResult("error");
				page.setMessage("上传excel销售类型参数不正确，请稍后重试");
			}else{
				GatewayUser user = (GatewayUser)session.getAttribute(Constants.SESSION_USER);
				inputStreams=creditInfomationService.getFileInputStream(myfiles);
				creditInfomationService.insertFinalPassDataToDB(inputStreams.get(0),user,agentType,session);
				logger.info("被保人清单读写成功");
				page.setResult("success");
				page.setMessage((String)session.getAttribute("result"));
			}
		} catch (Exception e) {
			logger.info("---------销售业务信息Excel导入失败",e);
			page.setResult("error");
			page.setMessage(e.getMessage());
		} finally {
			if(null!=inputStreams){
				for (InputStream input:inputStreams){
					try{
						input.close();
					}catch(Exception e){
						logger.warn("关闭流失败！", e);
					}
				}
			}
			out.write(JsonUtils.toJson(page));
			try {
				out.close();
			} catch (Exception e) {
				logger.warn("关闭流失败！", e);
			}
		}
	}
	
	// 归属渠道-渠道类型-新业务来源处理
	@RequestMapping(value = "/loadSubDropList")
	public @ResponseBody List<DictDto> getSubDropListData(String codeType, String parentCode) throws Exception {
		List<DictDto> list = new ArrayList<DictDto>();
		if (StrUtil.isNotEmpty(codeType) && StrUtil.isNotEmpty(parentCode)) {
			List<DictDto> subDataList = DictCache.getDictDataByParentCode(codeType, parentCode);
			//复制list
			list.addAll(subDataList);
			//倒序
			Collections.reverse(list);
			DictDto dd = new DictDto();
			dd.setCode("");
			dd.setCodeName("----请选择----");
			list.add(dd);
			//倒序
			Collections.reverse(list);
			return list;
		}else{
			DictDto dd = new DictDto();
			dd.setCode("");
			if("channel_type".equals(codeType)){
				dd.setCodeName("----请选择归属渠道----");
			}else if("new_business_source".equals(codeType)){
				dd.setCodeName("----请选择渠道类型----");
			}
			list.add(dd);
		}
		return list;
	}
	
	//选取旧业务来源
	@RequestMapping(value = "/chooseBsnsType")
	public @ResponseBody DictDto chooseBsnsType(String parentCode,String newBsnsCode) throws Exception {
		DictDto dd = new DictDto();
		if (StrUtil.isNotEmpty(parentCode)&&StrUtil.isNotEmpty(newBsnsCode)) {
			List<DictDto> subDataList = DictCache.getDictDataByParentCode("new_business_source", parentCode);
			for (DictDto dictDto : subDataList) {
				if(newBsnsCode.equals(dictDto.getCode())){
					return dictDto;
				}
			}
		}else{
			dd.setOtherCode("");
		}
		return dd;
	}
	/***
	 * 销售信息保存
	 */
	@RequestMapping(value = "/addTradSaleAgent")
	@ResponseBody
	public Result addTradSaleAgent(String id,String saleArry) throws Exception {
		return addTradSale(id, saleArry);
	}
	private Result addTradSale(String id,String saleArry) throws Exception{
		Result result = null;
		if(StrUtil.isNotEmpty(id)){
			Map<String, String> map=new HashMap<String, String>();
			map.put("id", id);
		/*	tradPlanSaleService.deleteTrade(map);*/
			agentInfoMtService.deleteTrade(id);
			List<Map<String,String>> list = JsonUtils.parseJson(saleArry, ArrayList.class);
			List<TradSaleAgent> planSales=new ArrayList<TradSaleAgent>();
			for (Map<String, String> map2 : list) {
				TradSaleAgent planSale=new TradSaleAgent();
				planSale.setAgentFee((Double.parseDouble(map2.get("agentFee"))+""));
				planSale.setAgentNo(map2.get("agentNo"));
				planSale.setEmpNo(map2.get("empNo"));
				planSale.setPersonType(map2.get("personType"));
				planSale.setPracticeNo(map2.get("practiceNo"));
				planSale.setSalePerson(map2.get("salePerson"));
				planSale.setSaleType(map2.get("saleType"));
				planSale.setSeqNo(map2.get("seqNo"));
				planSale.setPlanType(map2.get("planType"));
				planSale.setAgentCode(map2.get("agentCode"));
				planSale.setAgentName(map2.get("agentName"));
				planSale.setSaleName(map2.get("saleName"));
				planSale.setId(Long.parseLong(id));
				planSale.setInsertDate(new Date());
				planSales.add(planSale);
			}
			Boolean flag=agentInfoMtService.addTrade(planSales);
			if(flag){
				result=result.success("添加成功");
			}else{
				result=result.error("添加失败");	
			}
		}else{
			result=result.error("代理信息ID为空");
		}
		return result;
	
	}
	
	/**
	 * 查询业务员-团队信息(从销管获取)
	 * @param COMCODE
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/querySauserAndTeamInfo")
	@ResponseBody
	public Result querySauserAndTeamInfo(String COMCODE) throws Exception {
		if(StrUtil.isEmpty(COMCODE)){
			return Result.error("出单机构不能为空");
		}
		try{
			return nlifePlanConfigService.querySauserAndTeamInfo(COMCODE);
		}catch(Exception e){
			logger.info(e);
			return Result.error(e.getMessage());
		}
	}
	/**
	 * 加载机构列表，需要传入页面选择的“投保单位代码”进行查询
	 */
	@RequestMapping(value = "/loadCoreDept")
	public @ResponseBody Page<CoreDept> queryAllCoreDepts(HttpSession session , Integer size,Integer pageIndex,String deptCode,String deptCNname,String channelCode,String agentType) throws Exception{
		Page<CoreDept> page=new Page<CoreDept>();
		page.setCurrent(pageIndex);
		page.setSize(size);
		CoreDept dept=new CoreDept();
		GatewayUser gatewayuser=(GatewayUser) session.getAttribute(Constants.SESSION_USER);
		dept.setDeptCode(deptCode);
		dept.setDeptCname(deptCNname);
		page.setType(dept);
		Page<CoreDept> page2=agentInfoMtService.queryPageForCoreDept(page, channelCode, agentType , gatewayuser);
		return page2;
	}
	
	/**
	 * 加载所有 投保单位
	 * @param size
	 * @param current
	 * @return
	 * @throws Exception
	 * loadChannelInfo
	 */
	@RequestMapping(value = "/loadChannelInfo")
	public @ResponseBody Page<GatewayChannelInfo> loadChannelInfo(HttpSession session,Integer size,Integer pageIndex,String channelCode,String channelName,String flag) throws Exception{
		Page<GatewayChannelInfo> page = new Page<GatewayChannelInfo>();
		page.setCurrent(pageIndex);
		page.setSize(size);
		GatewayChannelInfo channelInfo = new GatewayChannelInfo();
		channelInfo.setChannelName(channelName);
		channelInfo.setChannelCode(channelCode);
		Map<String, Object> map =new HashMap<String, Object>();
		map.put("flag", flag);
		page.setMap(map);
		GatewayUser gatewayuser=(GatewayUser) session.getAttribute(Constants.SESSION_USER);
		page.setDepts(gatewayuser.getDepts());
		page.setType(channelInfo);
		Page<GatewayChannelInfo> p=gatewayInsureService.queryPageForGatewayChannelInfo(page);
		return p;
	}
	/***
	 * 查询机构列表
	 */

	/**
	 * 加载机构列表，需要传入页面选择的“投保单位代码”进行查询
	 */
	@RequestMapping(value = "/loadAgentDept")
	public @ResponseBody Page<CoreDept> queryAllCoreDepts(Page<CoreDept> page,String deptName ,String deptCode,HttpSession session,Integer pageIndex) throws Exception{
		GatewayUser user=(GatewayUser) session.getAttribute(Constants.SESSION_USER);
		Map<String, Object>map=new HashMap<String, Object>();
		/**条件判断*/
		if(StrUtil.isNotEmpty(deptCode)){
			map.put("deptCode", "%"+deptCode+"%");
		}
		if(StrUtil.isNotEmpty(deptName)){
			map.put("deptName","%"+ deptName+"%");
		}
		page.setMap(map);
		if(null != user && StrUtil.isNotEmpty(user.getDepartmentStr())){
			logger.info("登录用户"+user.getUserCode()+"用户机构"+user.getDepartmentStr());
			 page=gatewayInsureService.queryPageDept(page, user.getDepartmentStr());
			
		}
		return page;
	}
	/**
	 * 加载机构列表，需要传入页面选择的“投保单位代码”进行查询
	 */
	@RequestMapping(value = "/loadPlanFee")
	public @ResponseBody Page<TradePlanFee> queryPlanFee(Page<TradePlanFee> page,String planName ,String planNo, String deptCode,HttpSession session,Integer pageIndex,String agentInfoId) throws Exception{
		Map<String, Object>map=new HashMap<String, Object>();
		/**条件判断*/
		if(StrUtil.isNotEmpty(deptCode)){
			map.put("deptCode", deptCode);
		}
		if(StrUtil.isNotEmpty(planName)){
			map.put("planName",planName);
		}
		if(StrUtil.isNotEmpty(planNo)){
			map.put("planNo",planNo);
		}
		if(StrUtil.isNotEmpty(agentInfoId)){
			map.put("agentInfoId",agentInfoId);
		}
		page.setMap(map);
		logger.info("参数"+ planName+"-"+planNo+"-"+deptCode);
		try {
			page=tradPlanFeeService.queryPagePlanFee(page);
		} catch (Exception e) {
			logger.info(e);
		}
		return page;
	}
	/***
	 * 方案配置保存
	 */
	@RequestMapping(value = "/addTradPlanFee")
	@ResponseBody
	public Result addTradPlanFee(String planListStr,String agentInfoId,String planNosStr) throws Exception {
		try {
			return addTradPlan(planListStr, agentInfoId,planNosStr);
		} catch (Exception e) {
			logger.info(e);
			return Result.error("数据库错误");
		}
		
	}
	/**参数处理*/
	private String[] strToList(String str){
		if(StrUtil.isNotEmpty(str)){
			return str.split(",");
		}
		return null;
	}
	private Result addTradPlan(String planListStr,String agentInfoId,String planNosStr) throws Exception{
		Result result = null;
		if(StrUtil.isNotEmpty(agentInfoId)){
			Map<String, Object> map=new HashMap<String, Object>();
			map.put("agentInfoId", agentInfoId);
			map.put("planNos", strToList(planNosStr));
			/*gatewayInsureService.deleteCommPlanRate1(map);*/
			List<Map<String,String>> list = JsonUtils.parseJson(planListStr, ArrayList.class);
			List<TradAgentInfoRela> tradAgentInfoRelas=new ArrayList<TradAgentInfoRela>();
			for (Map<String, String> map2 : list) {
				TradAgentInfoRela planSale=new TradAgentInfoRela();
				planSale.setAgentInfoId(Long.parseLong(agentInfoId));
				if(null!=map2.get("busperRate")&&StrUtil.isNotEmpty(String.valueOf(map2.get("busperRate")))){
					planSale.setBusiness(new BigDecimal(String.valueOf(map2.get("busperRate"))));
				}
				if(null!=map2.get("commRate")&&StrUtil.isNotEmpty(String.valueOf(map2.get("commRate")))){
					planSale.setCommRate(new BigDecimal(String.valueOf(map2.get("commRate"))));
				}
				if(null!=map2.get("markperRate")&&StrUtil.isNotEmpty(String.valueOf(map2.get("markperRate")))){
					planSale.setMarket(new BigDecimal(String.valueOf(map2.get("markperRate"))));
				}
				planSale.setInsuPlanNo(map2.get("planNo"));
				planSale.setOperTime(new Date());
				tradAgentInfoRelas.add(planSale);
			}
			/**执行添加*/
			boolean flag=gatewayInsureService.addTradAgentInfoRelaBach(map, tradAgentInfoRelas);
			if(flag){
				result=result.success("配置成功");
			}else{
				result=result.error("配置失败");	
			}
		}else{
			result=result.error("代理信息ID为空");
		}
		return result;
	
	}
}
